//引用express框架
const express = require('express');
//导入文章集合
const { Article } = require('../model/article');
//导入分页模块
const pagination = require('mongoose-sex-page');
//创建博客展示页面路由
const home = express.Router();
//评论集合构造函数导入
const { Comment } = require('../model/comment')

//渲染首页
home.get('/', async(req, res) => {
    const page = req.query.page;
    let result = await pagination(Article).find().page(page).size(4).display(5).populate('author').exec();
    //渲染模板并传递数据
    res.render('home/default.art', {
        result: result
    });
});

// 博客前台文章详情页面
home.get('/article', async(req, res) => {
    //接收客户端传递过来的文章id
    const id = req.query.id;
    //根据id查询文章详情信息
    let article = await Article.findOne({ _id: id }).populate('author');
    //查询当前文章的评论信息
    let comments = await Comment.find({ aid: id }).papulate('uid');
    //渲染模板
    res.render('home/article', {
        article: article,
        comments: comments
    })
});

//创建用户评论功能
home.post('/comment', async(req, res) => {
    const { content, uid, aid } = req.body;

    //将评论信息储存到评论集合
    await Comment.create({
        content: conten,
        uid: uid,
        aid: aid,
        time: new Date()
    });
    //将文章页面定向文章详情页面
    res.redirect('/home/article?id=' + aid);
})




//将路由对象作为模块进行导出
module.exports = home;